package cc.linker.steplink.crm.controller;


import cc.linker.steplink.crm.commons.BeanMapUtils;
import cc.linker.steplink.crm.commons.constant.ContentConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.service.UserCenterService;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.domain.Awaken;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseCode;
import cc.linker.steplink.crm.response.ResponseException;
import cc.linker.steplink.crm.service.IAwakenService;
import cc.linker.steplink.crm.service.ILabelService;
import cc.linker.steplink.crm.service.ISysConfig;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * demo restful api
 * 智能唤醒
 *
 * @author huhj
 */
@Slf4j
@RestController
@RequestMapping("/awaken")
public class AwakenController {

    @Autowired
    private IAwakenService awakenService;

    @Autowired
    private ILabelService levelService;

    @Autowired
    private UserCenterService userCenterService;
    @Autowired
    private HttpService httpService;
    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private ISysConfig sysConfig;
    @Autowired
    private UserInfoUtil userInfoUtil;

    @PostMapping("/list")
    public Object list(@RequestBody Map<String, Object> map, HttpServletRequest request) throws GlobalException {
        int pn = 1, pageSize = 10;
        Object pno = map.get("pn");
        if (pno instanceof Integer && !StringUtils.isEmpty(pno)) {
            pn = (int) pno;
        }
        Object pageSizeo = map.get("pageSize");
        if (pageSizeo instanceof Integer && !StringUtils.isEmpty(pageSizeo)) {
            pageSize = (int) pageSizeo;
        }
        PageHelper.startPage(pn, pageSize);

        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);

        String orgId = userinfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        map.put("orgId", orgId);

        Date nowTime = new Date();

        List<Map<String, Object>> list = awakenService.listAwaken(map);
        if (null == list || 0 == list.size()) {
            list = new ArrayList<>();
            return new PageInfo<>(list);
        }
        for (Map<String, Object> stringObjectMap : list) {
            Object startTime = stringObjectMap.get("startTime");
            Object endTime = stringObjectMap.get("endTime");
            if (startTime instanceof Date) {

                if (!stringObjectMap.get("status").equals("3")) {
                    //开始时间小于当前时间  &&  开始时间小于结束时间  =>进行中
                    if (nowTime.getTime() > ((Date) startTime).getTime() && nowTime.getTime() < ((Date) endTime).getTime()) {
                        stringObjectMap.put("status", "2");
                    }
                    //结束时间小于当前时间  =>已完成
                    if (nowTime.getTime() > ((Date) endTime).getTime()) {
                        stringObjectMap.put("status", "1");
                    }
                    //开始时间大于当前时间  =>未开始
                    if (nowTime.getTime() < ((Date) startTime).getTime()) {
                        stringObjectMap.put("status", "0");
                    }
                }

            }

            if (stringObjectMap.get("intervalTime").equals(86400)) {
                stringObjectMap.put("intervalTime", "一天一次");
            }
            if (stringObjectMap.get("intervalTime").equals(604800)) {
                stringObjectMap.put("intervalTime", "一周一次");
            }
            if (stringObjectMap.get("intervalTime").equals(2592000)) {
                stringObjectMap.put("intervalTime", "一月一次");
            }
            String content = StringUtils.isEmpty(stringObjectMap.get("content")) ? null : stringObjectMap.get("content").toString();
            if (content != null) {
                stringObjectMap.put("pushData", content.split(","));
            } else {
                stringObjectMap.put("pushData", null);
            }
        }
        return new PageInfo<>(list);
    }


    /**
     * 添加任务
     *
     * @param session
     * @param map
     * @throws Exception
     */
    @PostMapping("/add")
    public void add(@RequestBody Map<String, Object> map,HttpServletRequest request) throws Exception {
        PcUserInfo userInfo = this.userInfoUtil.getPcUserInfo(request);
        map.put("articleId", map.get("classId").toString());//分类id
        map.put("content", map.get("labelIds"));//标签id。逗号分隔
        map.put("intervalTime", Integer.parseInt(map.get("intervalTimeVal").toString()));//频率
        map.put("taskId", UUID.randomUUID().toString());
        SimpleDateFormat utime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("updateTime", utime.format(new Date()));
        String orgId = userInfo.getOrgId();
        if (StringUtils.isEmpty(orgId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Integer wxCount = sysConfig.getWxCountByOrgId(orgId);
        if (wxCount < 1) {
            throw new GlobalException(new ResponseException(400, "当前机构下没有绑定公众号"));
        }
        String createUserId = userInfo.getAdminId();
        map.put("orgId", orgId);
        map.put("createUserId", createUserId);
        Awaken wake = BeanMapUtils.mapToBean(map, Awaken.class);
        awakenService.addAwaken(wake, StringUtils.isEmpty(map.get("labels")) ? "" : map.get("labels").toString());
    }


    /*
     * 删除任务
     */
    @PostMapping("/del")
    public void del( @RequestBody Map<String, Object> map) throws Exception {
        String taskId = (String) map.get("taskId");
        if (taskId.isEmpty()) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        Awaken wake = BeanMapUtils.mapToBean(map, Awaken.class);
        awakenService.delAwaken(wake);
    }

    /*
     * 编辑任务
     */
    @PostMapping("/edit")
    public void edit( HttpServletRequest request, @RequestBody Map<String, Object> map) throws Exception {
        map.put("articleId", map.get("classId").toString());//分类id
        map.put("content", map.get("labelIds"));//标签id。逗号分隔
        map.put("intervalTime", Integer.parseInt(map.get("intervalTimeVal").toString()));//频率
        String taskId = (String) map.get("taskId");
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if (StringUtils.isEmpty(userinfo.getOrgId())) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Integer wxCount = sysConfig.getWxCountByOrgId(userinfo.getOrgId());
        if (wxCount < 1) {
            throw new GlobalException(new ResponseException(400, "当前机构下没有绑定公众号"));
        }
        map.put("orgId", userinfo.getOrgId());
        if (taskId.isEmpty()) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        Map<String, Object> info = awakenService.getAwaken(map).get(0);
        Object startTime = info.get("startTime");
        Object endTime = info.get("endTime");
        Date nowTime = new Date();
        if (nowTime.getTime() > ((Date) startTime).getTime() && nowTime.getTime() < ((Date) endTime).getTime()) {
            throw new GlobalException(new ResponseException(400, "任务已经被执行，无法保存"));
        }

        SimpleDateFormat utime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("updateTime", utime.format(new Date()));
        Awaken wake = BeanMapUtils.mapToBean(map, Awaken.class);
        awakenService.editAwaken(wake, StringUtils.isEmpty(map.get("labels")) ? "" : map.get("labels").toString());
    }

    /*
     * 编辑任务
     */
    @PostMapping("/gettaskinfo")
    public Object getTaskInfo(@RequestBody Map<String, Object> map) throws Exception {
        String taskId = (String) map.get("taskId");
        if (taskId.isEmpty()) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        Map<String, Object> info = awakenService.getAwaken(map).get(0);
        if (info.get("intervalTime").equals(86400)) {
            info.put("intervalTimeVal", 86400);
            info.put("intervalTime", "一天一次");
        }
        if (info.get("intervalTime").equals(604800)) {
            info.put("intervalTimeVal", 604800);
            info.put("intervalTime", "一周一次");
        }
        if (info.get("intervalTime").equals(2592000)) {
            info.put("intervalTimeVal", 2592000);
            info.put("intervalTime", "一月一次");
        }

        String content = StringUtils.isEmpty(info.get("content")) ? null : info.get("content").toString();
        if (content != null) {
            info.put("pushData", content.split(","));
        } else {
            info.put("pushData", null);
        }
        info.put("classId", info.get("articleId") == null || info.get("articleId").toString().equals("") ? "" : Integer.parseInt(info.get("articleId").toString()));
        info.remove("articleId");
        info.remove("content");
        return info;
    }


    @GetMapping("/getinterval")
    public Object getInterval(HttpSession session) throws Exception {

        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("key", "一天一次");
        map1.put("val", 86400);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("key", "一周一次");
        map2.put("val", 604800);
        Map<String, Object> map3 = new HashMap<>();
        map3.put("key", "一月一次");
        map3.put("val", 2592000);
        list.add(map1);
        list.add(map2);
        list.add(map3);
        return list;
    }


    @Value("${system.scrm.sync.contentUrl}")
    private String awakenclassurl;

    @GetMapping("/getarticleclass")
    public Object getArticleClass() throws Exception {
        String url = systemProperties.getSync().getContentUrl() + ContentConstant.GET_RESOURCE_CLASSIFICATION;
        String res = httpService.doGet(url, null, ContentConstant.HEADER);
        Map map = (Map) JSON.parse(res);
        if (!map.get("code").equals("200")) {
            throw new GlobalException(ResponseCode.FAIL);
        }
        return map.get("data");
    }

    @GetMapping("/getarticlelabels")
    public Object getArticleLabels(HttpServletRequest request) throws Exception {
        PcUserInfo userInfo = this.userInfoUtil.getPcUserInfo(request);
        List<Map<String, Object>> data = levelService.getArticleLabelsByOrgId(userInfo.getOrgId());
        if (null != data) {
            return data;
        }
        return new ArrayList<>();
    }


    @Value("${system.scrm.sync.contentUrl}")
    private String awakenarticleurl;

    @GetMapping("/getawakenarticle")
    public Object awakenArticleList(HttpServletRequest request) throws GlobalException, IOException, URISyntaxException {
        PcUserInfo userInfo = this.userInfoUtil.getPcUserInfo(request);
        int pn = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pn")) ? "1" : request.getParameter("pn"));
        int pageSize = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageSize")) ? "10" : request.getParameter("pageSize"));

        String classId = request.getParameter("classId");
        String labels = request.getParameter("labels");
        String orgId = userInfo.getOrgId();
        String adminId = userInfo.getAdminId();
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", pn);
        map.put("perPage", pageSize);

        /* 2019-09-27修改
        * 获取当前机构下所有符合搜索条件的文章
        */
//        map.put("userId", adminId);


        if (null != classId) {
            map.put("classificationId", classId);
        }
        if (null != labels) {
            map.put("labelName", labels);
        }
        if (!orgId.isEmpty()) {
            map.put("organizationNum", orgId);
        }


        String url = systemProperties.getSync().getContentUrl() + ContentConstant.NEWS_BY_STEP;
        String res = httpService.doPost(url, map, ContentConstant.HEADER);
        if(StringUtils.isEmpty(res)){
            throw GlobalException.build("内容库没有响应");
        }
        Map data = (Map) JSON.parse(res);
        if (!"200".equals(data.get("code"))) {
            LOGGER.error("调用错误" + JSON.toJSONString(res));
            if("没有查询到符合条件的营销号".equals(data.get("message").toString())){
                data.put("message","请先创建营销号");
            }
            throw GlobalException.build(data.get("message").toString());
        }
        Map<String, Object> rsMap = new HashMap<>();
        rsMap.put("count", data.get("count"));
        rsMap.put("pn", data.get("pageIndex"));
        rsMap.put("pageSize", data.get("perPage"));
        rsMap.put("totalPage", data.get("totalPage"));
        rsMap.put("list", data.get("data"));
        return rsMap;
    }

}
